package cn.cloudmenu.android.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.cloudmenu.android.MenuCategoryBean;
import cn.cloudmenu.android.R;

public class Categories extends ListActivity {
	private ArrayList<MenuCategoryBean> MenuCategories = new ArrayList<MenuCategoryBean>();
	
	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Bitmap mIcon;

		public EfficientAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);

			// Icons bound to the rows.
			mIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.book);
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return MenuCategories.size();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return MenuCategories.get(position);
		}

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.categories_list_item_icon_text, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.category_name);
				holder.icon = (ImageView) convertView.findViewById(R.id.category_icon);

				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			holder.name.setText(MenuCategories.get(position).getTagName());
			holder.icon.setImageBitmap(mIcon);

			return convertView;
		}

		class ViewHolder {
			TextView name;
			ImageView icon;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.categories);
		// 从服务器获取菜单菜品分类信息
		MenuCategories.clear();
		this.loadMenuCategories();
				
		System.out.println("Categories.onCreate().................1");
		setListAdapter(new EfficientAdapter(this));
		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		System.out.println("Categories.onCreate().................2");
		// 为ListView设置列表项点击监听器
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				System.out.println("Categories ItemClickListener.onItemClick()..................................................................................");
				MenuCategoryBean category = (MenuCategoryBean) parent.getItemAtPosition(position);
				Intent intent = new Intent(Categories.this, Courses.class);
				intent.putExtra("tagId", category.getTagId());
				intent.putExtras(Categories.this.getIntent());
				System.out.println("Categories ItemClickListener.onItemClick() Categories.this.getIntent() menuId="+Categories.this.getIntent().getIntExtra("menuId", -1));
				System.out.println("Categories ItemClickListener.onItemClick() Categories.this.getIntent() tableName="+Categories.this.getIntent().getStringExtra("tableName"));
				System.out.println("Categories ItemClickListener.onItemClick() Categories.this.getIntent() opener="+Categories.this.getIntent().getStringExtra("opener"));
				System.out.println("Categories ItemClickListener.onItemClick() category.getMenuId() = "+category.getMenuId()+" category.getTagId() = "+category.getTagId()+"..................................................................................");
				Categories.this.startActivity(intent);
			}
		});
	}

	public void orderedList(View view) {
		System.out.println("Courses.orderedList(view) is called! view.getTag() = " + view.getTag());
		this.outExtras();
		Intent intent = new Intent(this, CoursesOrdered.class);
		intent.putExtras(getIntent());
		this.startActivity(intent);
	}

	private void outExtras(){
		Intent intent = getIntent();
		Set<String> keys = intent.getExtras().keySet();
		for(String key : keys){
			System.out.println(key +" = "+intent.getExtras().get(key));
		}
	}
	
	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 2);
		t1.show();
	}
	
	private boolean loadMenuCategories() {
		String href = getResources().getString(R.string.menu_categories);
		Integer menuId = getIntent().getIntExtra("menuId", -1);
		if(menuId.equals(-1L)) return false;
		href = href + menuId;
		System.out.println("Categories.loadMenuCategories() href = " + href);
		HttpPost request = new HttpPost(href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			
			// 生成 JSON 对象
			JSONArray menuCategories = new JSONArray(retSrc);
			System.out.println("Categories.loadMenuCategories() menuCategories.length = " + menuCategories.length());
			if (menuCategories.length() < 1) {
				Intent intent = new Intent(this, FavoriteMenu.class);
				this.startActivity(intent);
				return false;
			}else{
				for(int i=0; i<menuCategories.length(); i++){
					JSONObject category = menuCategories.getJSONObject(i);
					MenuCategoryBean cb = new MenuCategoryBean();
					MenuCategories.add(cb);
					cb.setMenuId(menuId);
					cb.setTagId(category.getInt("id"));
					cb.setTagName(category.getString("name"));
					cb.setStoreId(category.getInt("storeId"));
					cb.setUpdateTime(new Date(category.getLong("updateTime")));
					cb.setDescription(category.getString("description"));
				}
				return true;
			}
		} catch (Exception e) {
			displayMessage(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
}